<template>
    <div class="teacher-attendance-stats">
        <div class="breadcrumb">
            <span>考勤管理</span> &gt; <span>教师考勤</span> &gt; <span>考勤统计</span>
        </div>

        <div class="tabs">
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/manage')">我的请假</div>
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/approval')">请假审批</div>
            <div class="tab-item active">考勤统计</div>
            <div class="tab-item" @click="navigateTo('/main/teacher-attendance/time-setting')">考勤时间设置</div>
        </div>

        <div class="filter-bar">
            <el-select v-model="semester" placeholder="学期考勤" class="filter-item">
                <el-option label="2023-2024学年第一学期" value="2023-2024-1" />
                <el-option label="2023-2024学年第二学期" value="2023-2024-2" />
                <el-option label="2022-2023学年第一学期" value="2022-2023-1" />
                <el-option label="2022-2023学年第二学期" value="2022-2023-2" />
            </el-select>

            <el-select v-model="month" placeholder="月份考勤" class="filter-item">
                <el-option v-for="i in 12" :key="i" :label="`${i}月`" :value="i" />
            </el-select>

            <el-select v-model="department" placeholder="部门" class="filter-item">
                <el-option v-for="item in departmentList" :key="item.id" :label="item.departmentName"
                    :value="item.id" />
            </el-select>

            <el-input v-model="keyword" placeholder="姓名/编号" class="filter-item" clearable />

            <el-button type="primary" @click="handleSearch" class="search-btn">查 询</el-button>
            <el-button @click="handleReset" class="reset-btn">重 置</el-button>
            <el-button type="warning" @click="exportData" class="export-btn">导出数据</el-button>
        </div>

        <div class="statistics-cards">
            <el-card class="stat-card">
                <template #header>
                    <div class="card-header">
                        <span>出勤率</span>
                    </div>
                </template>
                <div class="stat-value">{{ statisticsSummary.attendanceRate || '0%' }}</div>
            </el-card>
            <el-card class="stat-card">
                <template #header>
                    <div class="card-header">
                        <span>病假率</span>
                    </div>
                </template>
                <div class="stat-value">{{ statisticsSummary.sickLeaveRate || '0%' }}</div>
            </el-card>
            <el-card class="stat-card">
                <template #header>
                    <div class="card-header">
                        <span>事假率</span>
                    </div>
                </template>
                <div class="stat-value">{{ statisticsSummary.personalLeaveRate || '0%' }}</div>
            </el-card>
        </div>

        <div class="result-info">查询结果：共计 {{ tableData.length }} 条数据</div>

        <el-table :data="tableData" border style="width: 100%" v-loading="loading">
            <el-table-column prop="department" label="部门" min-width="100" align="center" />
            <el-table-column prop="name" label="姓名" min-width="100" align="center" />
            <el-table-column prop="id" label="编号" min-width="120" align="center" />
            <el-table-column prop="actualAttendance" label="实际出勤天数" min-width="120" align="center" />
            <el-table-column label="迟到次数" min-width="100" align="center">
                <template #default="scope">
                    <el-link type="primary" v-if="scope.row.lateTimes > 0" @click="showDetailDialog('late', scope.row)">
                        {{ scope.row.lateTimes }}
                    </el-link>
                    <span v-else>{{ scope.row.lateTimes }}</span>
                </template>
            </el-table-column>
            <el-table-column label="早退次数" min-width="100" align="center">
                <template #default="scope">
                    <el-link type="primary" v-if="scope.row.earlyLeaveTimes > 0"
                        @click="showDetailDialog('earlyLeave', scope.row)">
                        {{ scope.row.earlyLeaveTimes }}
                    </el-link>
                    <span v-else>{{ scope.row.earlyLeaveTimes }}</span>
                </template>
            </el-table-column>
            <el-table-column label="缺卡次数" min-width="100" align="center">
                <template #default="scope">
                    <el-link type="primary" v-if="scope.row.missedCardTimes > 0"
                        @click="showDetailDialog('missedCard', scope.row)">
                        {{ scope.row.missedCardTimes }}
                    </el-link>
                    <span v-else>{{ scope.row.missedCardTimes }}</span>
                </template>
            </el-table-column>
            <el-table-column label="外勤天数" min-width="100" align="center">
                <template #default="scope">
                    <el-link type="primary" v-if="scope.row.externalWorkDays > 0"
                        @click="showDetailDialog('externalWork', scope.row)">
                        {{ scope.row.externalWorkDays }}
                    </el-link>
                    <span v-else>{{ scope.row.externalWorkDays }}</span>
                </template>
            </el-table-column>
            <el-table-column label="请假次数" min-width="100" align="center">
                <template #default="scope">
                    <el-link type="primary" v-if="scope.row.leaveTimes > 0"
                        @click="showDetailDialog('leave', scope.row)">
                        {{ scope.row.leaveTimes }}
                    </el-link>
                    <span v-else>{{ scope.row.leaveTimes }}</span>
                </template>
            </el-table-column>
        </el-table>

        <!-- 详情弹窗 -->
        <el-dialog v-model="detailDialogVisible" :title="detailDialogTitle" width="650px">
            <el-table :data="detailData" border style="width: 100%">
                <el-table-column prop="date" label="日期" min-width="120" align="center" />
                <el-table-column prop="time" label="时间" min-width="120" align="center" />
                <el-table-column prop="type" label="类型" min-width="100" align="center" />
                <el-table-column prop="duration" label="时长" min-width="100" align="center"
                    v-if="currentDetailType === 'leave'" />
                <el-table-column prop="reason" label="原因" min-width="200" align="center" />
            </el-table>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="detailDialogVisible = false">关闭</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import { getDepartmentList, exportTeacherAttendanceData } from '@/api/teacherKaoqin'

const router = useRouter()
const loading = ref(false)

// 查询条件
const semester = ref('')
const month = ref('')
const department = ref('')
const keyword = ref('')

// 部门列表
const departmentList = ref<any[]>([])

// 统计数据
const tableData = ref<any[]>([])

// 统计汇总
const statisticsSummary = reactive({
    attendanceRate: '96.5%',
    sickLeaveRate: '2.1%',
    personalLeaveRate: '1.4%'
})

// 详情弹窗相关
const detailDialogVisible = ref(false)
const detailDialogTitle = ref('')
const detailData = ref<any[]>([])
const currentDetailType = ref('')

// 获取部门列表
async function fetchDepartmentList() {
    try {
        const response: any = await getDepartmentList()
        if (response.data && response.data.code === 200) {
            departmentList.value = response.data.data
        }
    } catch (error) {
        console.error('获取部门列表失败:', error)
    }
}

// 获取统计数据
function fetchStatisticsData() {
    loading.value = true

    // 在实际应用中，应该调用API获取数据
    // 这里使用模拟数据
    setTimeout(() => {
        tableData.value = [
            {
                department: '教职工',
                name: '张爱国',
                id: '324323131',
                actualAttendance: 105,
                lateTimes: 1,
                earlyLeaveTimes: 0,
                missedCardTimes: 1,
                externalWorkDays: 2,
                leaveTimes: 3
            },
            {
                department: '语文组',
                name: '李明',
                id: '324323132',
                actualAttendance: 110,
                lateTimes: 0,
                earlyLeaveTimes: 1,
                missedCardTimes: 0,
                externalWorkDays: 1,
                leaveTimes: 2
            },
            {
                department: '数学组',
                name: '王强',
                id: '324323133',
                actualAttendance: 112,
                lateTimes: 2,
                earlyLeaveTimes: 0,
                missedCardTimes: 0,
                externalWorkDays: 0,
                leaveTimes: 1
            }
        ]

        // 在实际应用中，这些统计数据应该由服务器计算并返回
        statisticsSummary.attendanceRate = '96.5%'
        statisticsSummary.sickLeaveRate = '2.1%'
        statisticsSummary.personalLeaveRate = '1.4%'

        loading.value = false
    }, 500)
}

// 查询
function handleSearch() {
    fetchStatisticsData()
    ElMessage.success('查询成功')
}

// 重置
function handleReset() {
    semester.value = ''
    month.value = ''
    department.value = ''
    keyword.value = ''
    fetchStatisticsData()
}

// 导出数据
function exportData() {
    // 收集导出条件
    const params = {
        semester: semester.value,
        month: month.value,
        department: department.value,
        keyword: keyword.value
    }

    // 在实际应用中，应该调用API导出数据
    exportTeacherAttendanceData(params)
        .then((response: any) => {
            if (response.data && response.data.code === 200) {
                ElMessage.success('导出成功，请在下载中心查看')
            } else {
                ElMessage.error(response.data?.message || '导出失败')
            }
        })
        .catch(error => {
            console.error('导出失败:', error)
            ElMessage.error('导出失败')
        })
}

// 显示详情弹窗
function showDetailDialog(type: string, row: any) {
    currentDetailType.value = type

    if (type === 'late') {
        detailDialogTitle.value = `${row.name} - 迟到详情`
        detailData.value = [
            { date: '2023-05-15', time: '08:35:42', type: '迟到', reason: '交通拥堵' }
        ]
    } else if (type === 'earlyLeave') {
        detailDialogTitle.value = `${row.name} - 早退详情`
        detailData.value = [
            { date: '2023-05-18', time: '16:30:00', type: '早退', reason: '家中有事' }
        ]
    } else if (type === 'missedCard') {
        detailDialogTitle.value = `${row.name} - 缺卡详情`
        detailData.value = [
            { date: '2023-05-20', time: '17:30:00', type: '下班缺卡', reason: '忘记打卡' }
        ]
    } else if (type === 'externalWork') {
        detailDialogTitle.value = `${row.name} - 外勤详情`
        detailData.value = [
            { date: '2023-05-10', time: '全天', type: '外勤', reason: '参加教研活动' },
            { date: '2023-05-11', time: '全天', type: '外勤', reason: '参加培训' }
        ]
    } else if (type === 'leave') {
        detailDialogTitle.value = `${row.name} - 请假详情`
        detailData.value = [
            { date: '2023-05-02', time: '全天', type: '病假', duration: '1天', reason: '感冒发烧' },
            { date: '2023-05-25', time: '下午', type: '事假', duration: '0.5天', reason: '家中有事' },
            { date: '2023-05-30', time: '上午', type: '事假', duration: '0.5天', reason: '银行办理业务' }
        ]
    }

    detailDialogVisible.value = true
}

// 导航到指定路由
function navigateTo(route: string) {
    router.push(route)
}

// 组件挂载时初始化
onMounted(() => {
    fetchDepartmentList()
    fetchStatisticsData()
})
</script>

<style scoped>
.teacher-attendance-stats {
    padding: 0 20px;
}

.breadcrumb {
    display: flex;
    align-items: center;
    height: 50px;
    font-size: 14px;
    color: #606266;
}

.tabs {
    display: flex;
    border-bottom: 1px solid #e4e7ed;
    margin-bottom: 20px;
}

.tab-item {
    padding: 12px 20px;
    font-size: 14px;
    cursor: pointer;
    color: #606266;
    border-bottom: 2px solid transparent;
}

.tab-item.active {
    color: #409EFF;
    border-bottom: 2px solid #409EFF;
}

.filter-bar {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
    margin-bottom: 20px;
    align-items: center;
}

.filter-item {
    width: 180px;
}

.search-btn,
.reset-btn,
.export-btn {
    margin-left: 10px;
}

.statistics-cards {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.stat-card {
    width: 32%;
}

.card-header {
    font-weight: bold;
}

.stat-value {
    font-size: 24px;
    text-align: center;
    padding: 20px 0;
    color: #409EFF;
    font-weight: bold;
}

.result-info {
    background-color: #ecf8ff;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 4px;
    color: #409EFF;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
}
</style>